package com.dotmedia.dboperations;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.ejb.CurrentEntityManagerImpl;

import com.dotmedia.core.DatabaseAccessService;
import com.dotmedia.entities.User;

/**
 * This class has the method to deal with the database operations for the User entity objects
 * 
 * @author siddharthsaha
 * 
 */
public class UserDatabaseOperations {

	private static Logger logger = Logger.getLogger("UserDatabaseOperations");

	/**
	 * This method will persist a user entity into the database
	 * 
	 * @param userEntity
	 *        This method persists a user into the database
	 */
	public void persistUserEntity(User userEntity) {
		logger.info("IN method persistUserEntity() in UserDatabaseOperations");
		DatabaseAccessService databaseAccessService = DatabaseAccessService.getInstance();
		int persistStatus = databaseAccessService.persistEntity(userEntity);
		if (persistStatus == 0) {
			logger.info("User entity persisted into the database. User Ext id: " + userEntity.getUserExtId());
		} else {
			logger.error("User entity persisted into the database. User Ext id: " + userEntity.getUserExtId());
		}
		logger.info("OUT method persistUserEntity() in UserDatabaseOperations");
	}

	/**
	 * This method will remove a user entity from the database.
	 * 
	 * @param userEntity
	 *        The user entity that needs to be removed from the database
	 */
	public void removeUserEntity(User userEntity) {
		logger.info("IN method removeUserEntity() in UserDatabaseOperations");
		DatabaseAccessService databaseAccessService = DatabaseAccessService.getInstance();
		int removeStatus = databaseAccessService.removeEntity(userEntity, userEntity.getId());
		if (removeStatus == 0) {
			logger.info("User entity was successfully removed from the database. User Ext id: " + userEntity.getUserExtId());
		} else {
			logger.info("User entity could not be removed from the database. User Ext id: " + userEntity.getUserExtId());
		}
		logger.info("OUT method removeUserEntity() in UserDatabaseOperations");
	}

	/**
	 * This method will update a user entity in the database
	 * 
	 * @param userEntity
	 *        The user entity that needs to be updated in the database
	 */
	public void updateUserEntity(User userEntity) {
		logger.info("IN method updateUserEntity() in UserDatabaseOperations");
		DatabaseAccessService databaseAccessService = DatabaseAccessService.getInstance();
		String query = "SELECT userEntity FROM User userEntity WHERE userEntity.id = " + userEntity.getId();
		logger.info("Query: " + query);
		List retrivedEntities = databaseAccessService.getEntities(query);
		boolean obtained = false;
		for (int retreivedEntitiesIndex = 0; retreivedEntitiesIndex < retrivedEntities.size(); retreivedEntitiesIndex++) {
			User currentUserEntity = (User) retrivedEntities.get(retreivedEntitiesIndex);
			if (currentUserEntity.getId().intValue() == userEntity.getId().intValue()) {
				obtained = true;
				logger.info("The User entity to be updated was obtained");
				currentUserEntity.setEmail(userEntity.getEmail());
				currentUserEntity.setExpireOn(userEntity.getExpireOn());
				currentUserEntity.setName(userEntity.getName());
				currentUserEntity.setPassword(userEntity.getPassword());
				currentUserEntity.setRole(userEntity.getRole());
				currentUserEntity.setSurname(userEntity.getSurname());
				currentUserEntity.setUiTranslation(userEntity.getUiTranslation());
				currentUserEntity.setSystem(userEntity.getSystem());
				int updateStatus = databaseAccessService.updateEntity(currentUserEntity);
				if (updateStatus == 0) {
					logger.info("The user entity was successfully updated. User ext id: " + userEntity.getUserExtId());
				} else {
					logger.error("The user entity cannot be successfully updated. User ext id: " + userEntity.getUserExtId());
				}
				break;
			}
		}
		if (!obtained) {
			logger.warn("The User entity to be updated could not be found");
		}
		logger.info("OUT method updateUserEntity() in UserDatabaseOperations");
	}

	/**
	 * This method will get the user entities with a specific user ext id
	 * 
	 * @param userExtId
	 *        The user ext id which needs to be found
	 * @return
	 */
	public List<User> getUserEntitiesWithExtId(String userExtId) {
		logger.info("IN method getUserEntitiesWithExtId() in UserDatabaseOperations");
		List<User> toReturnEntities = new ArrayList<User>();
		String query = "SELECT userEntity FROM User userEntity where userEntity.userExtId = '" + userExtId + "'";
		logger.info("Query: " + query);
		DatabaseAccessService databaseAccessService = DatabaseAccessService.getInstance();
		List retrievedEntities = databaseAccessService.getEntities(query);
		for (int retreivedEntitesIndex = 0; retreivedEntitesIndex < retrievedEntities.size(); retreivedEntitesIndex++) {
			User currentUserEntity = (User) retrievedEntities.get(retreivedEntitesIndex);
			if (currentUserEntity.getUserExtId().equals(userExtId)) {
				toReturnEntities.add(currentUserEntity);
			}
		}
		logger.info("OUT method getUserEntitiesWithExtId() in UserDatabaseOperations");
		return toReturnEntities;
	}

	/**
	 * This method returns the user entities with a specific lang code
	 * 
	 * @param langCode
	 *        The lang code whose entities are required
	 * @return
	 */
	public List<User> getUserEntitiesWithLangCode(String langCode) {
		logger.info("IN method getUserEntitiesWithLangCode() in UserDatabaseOperations");
		List<User> toReturnEntities = new ArrayList<User>();
		String query = "SELECT userEntity FROM User userEntity where userEntity.uiTranslation.system.defaultLangCode = '" + langCode + "'";
		logger.info("Query: " + query);
		DatabaseAccessService databaseAccessService = DatabaseAccessService.getInstance();
		List retrievedEntities = databaseAccessService.getEntities(query);
		for (int retrievedEntitiesIndex = 0; retrievedEntitiesIndex < retrievedEntities.size(); retrievedEntitiesIndex++) {
			User currentUserEntity = (User) retrievedEntities.get(retrievedEntitiesIndex);
			if (currentUserEntity.getUiTranslation().getLangCode().equals(langCode)) {
				toReturnEntities.add(currentUserEntity);
			}
		}
		logger.info("OUT method getUserEntitiesWithLangCode() in UserDatabaseOperations");
		return toReturnEntities;
	}

	/**
	 * This method returns the user entities with a particular role ext id
	 * 
	 * @param roleExtId
	 *        The role ext id whose users are asked for
	 * @return
	 */
	public List<User> getUsersWithRoleExtId(String roleExtId) {
		logger.info("IN method getUsersWithRoleExtId() in UserDatabaseOperations");
		List<User> toReturnEntities = new ArrayList<User>();
		String query = "SELECT userEntity FROM User userEntity WHERE userEntity.role.roleExtId = '" + roleExtId + "'";
		logger.info("Query: " + query);
		DatabaseAccessService databaseAccessService = DatabaseAccessService.getInstance();
		List retrievedEntities = databaseAccessService.getEntities(query);
		for (int retrievedEntitiesIndex = 0; retrievedEntitiesIndex < retrievedEntities.size(); retrievedEntitiesIndex++) {
			User currentUserEntity = (User) retrievedEntities.get(retrievedEntitiesIndex);
			if (currentUserEntity.getRole().getRoleExtId().equals(roleExtId)) {
				toReturnEntities.add(currentUserEntity);
			}
		}
		logger.info("OUT method getUsersWithRoleExtId() in UserDatabaseOperations");
		return toReturnEntities;
	}

}
